package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

	@Autowired
	private UserInfoMapper userInfoMapper;
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private UserPaidAlbumMapper userPaidAlbumMapper;
    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    /**
     * @author gengjian
     * @date 2025/02/24 21:04:23
     * 微信登录
     */
    @Override
    public Map<String, String> wxLogin(String code) {
        //声明一个map集合
        Map<String,String> map = new HashMap<>();
        WxMaJscode2SessionResult wxMaJscode2SessionResult = null;
        try {
            wxMaJscode2SessionResult = wxMaService.jsCode2SessionInfo(code);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        //获取到了微信用户对应的微信标识
        String openid = wxMaJscode2SessionResult.getOpenid();
        //通过这个openid，查询用户信息，如果有对应的信息记录，则说明用户已经存在，如果没有则说明用户未注册，实现注册功能并初始化账户金额
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openid));
        if (ObjectUtils.isEmpty(userInfo)) {
            //第一次注册 初始化用户数据openid 用户头像 用户昵称
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openid);
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            userInfo.setNickname("用户" + UUID.randomUUID().toString().replaceAll("-", ""));
            //添加到表中
            userInfoMapper.insert(userInfo);
            //发送一个消息，账户金额初始化
            rabbitService.sendMessage(MqConst.EXCHANGE_USER, MqConst.ROUTING_USER_REGISTER, userInfo.getId());
        }
        //已注册 生成token直接存储到缓存，并返回一个token
        String token = UUID.randomUUID().toString().replaceAll("-","");
        String userLoginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        redisTemplate.opsForValue().set(userLoginKey,userInfo,RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
        //存储token
        map.put("token",token);
        //返回数据
        return map;
    }
    /**
     * @author gengjian
     * @date 2025/02/26 17:11:50
     * 根据用户id获取用户信息
     */
    @Override
    public UserInfoVo getUserInfo(Long userId) {
        //封装用户vo
        UserInfoVo userInfoVo = new UserInfoVo();
        UserInfo userInfo = userInfoMapper.selectById(userId);
        BeanUtils.copyProperties(userInfo,userInfoVo);
        return userInfoVo;
    }

    /**
     * 判断用户是否购买声音列表
     * @param albumId
     * @param trackIdList
     * @return
     */
    @Override
    public Map<Long, Integer> userIsPaidTrack(List<Long> trackIdList, Long albumId, Long userId) {
        //创建map集合
        Map<Long,Integer> map = new HashMap<>();
        //通过用户id查用户是否购买专辑 user_paid_album
        UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(
                new LambdaQueryWrapper<UserPaidAlbum>()
                        .eq(UserPaidAlbum::getUserId, userId)
                        .eq(UserPaidAlbum::getAlbumId, albumId));
        if (!ObjectUtils.isEmpty(userPaidAlbum)){
            //用户购买过此专辑 则将所以付费声音设置为已购买 转换成map结构
            return trackIdList.stream().collect(Collectors.toMap(trackId -> trackId, trackId -> 1));
        }
        //通过用户id和专辑id查购买的声音列表 user_paid_track
        List<UserPaidTrack> userPaidTrackList = userPaidTrackMapper.selectList(
                new LambdaQueryWrapper<UserPaidTrack>()
                        .eq(UserPaidTrack::getUserId, userId)
                        .eq(UserPaidTrack::getAlbumId, albumId));
        //将List<UserPaidTrack>转换为list<long>
        List<Long> list = userPaidTrackList.stream().map(UserPaidTrack::getTrackId).toList();
        if (CollectionUtils.isEmpty(userPaidTrackList)){
            //说明用户没买过 都设置成未购买
            return trackIdList.stream().collect(Collectors.toMap(trackId->trackId,trackId->0));
        }else {
            //用户买过声音 遍历需要付费集合 买过的设置为1 未买过设置为0
            for (Long trackId : trackIdList) {
                if (list.contains(trackId)){
                    map.put(trackId,1);
                }else {
                    map.put(trackId,0);
                }
            }
        }
        return map;
    }
}
